package com.keeley.ctrl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang.ArrayUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;
import com.jfinal.token.TokenManager;
import com.keeley.content.Content;
import com.keeley.interceptor.Seach;
import com.keeley.model.SeachModel;
import com.keeley.model.User;
import com.keeley.model.VestCommon;
import com.keeley.pageModel.DataGrid;
import com.keeley.pageModel.TreeNode;
/**
 * 
 * @author Tianjun
 * @date 2014年5月17日
 * 后台控制层公共类
 * @param <M>
 */
public class AdminBaseController<M extends SeachModel<M>>  extends Controller{
	public Logger log=Logger.getLogger(getClass());
	protected Model<M> po;
	protected Class<M> modelClass;
	protected static String tokenName="token";
	protected int tokenTout=600; 
	protected Table table;
	
	@Before(Seach.class)
	public void grid(){
		Seach seach = getAttr("seachBean");
		int page=getParaToInt("page", 1);
		int rows=this.getParaToInt("rows", 20);
		otherSeach(seach);
		try {
			Page<M> date=modelClass.newInstance().paginate(page,rows,seach);
			rendDataGrid(date);
		} catch (Exception e) {
			log.error(e);
			rendJson_(false, e.getMessage());
		}
	}
	
	public AdminBaseController(Class<M> modelClass) {
		super();
		this.modelClass = modelClass;
		if(modelClass!=null)
			this.table = TableMapping.me().getTable(this.modelClass);
	}
	public void index(){
	}
	public Model<M> get(Long id) {
		
		Model<M> model_;
		try {
			model_ = modelClass.newInstance();
			return model_.findById(id);//Db.findById(this.tableName, id);
		} catch (Exception e) {
		}
		return null;
	}
	public void view() {
		Long id= this.getParaToLong(0,0L);
		if(id!=null&&id!=0L)
			this.setAttr("po",get(id));
		else
			this.setAttr("po",new Record());
	}
	public void edit() {
		try {
			Long id = this.getParaToLong(0, 0L);
			if (id != 0L) {
				po = get(id);
			}else{
				setAttr("now",new Date());
			}
			TokenManager.createToken(this, tokenName, tokenTout);
			 this.setAttr("po",po);
		} catch (Exception e) {
			log.error("编辑异常", e);
		}
	}
	public User getCurrentUser(){
		return getSessionAttr(Content.SESSION_LOGIN_USER);
	}
	public void save() {
		String msg;
		try {
			Model<M> m = this.getModel(modelClass);
			Integer id = m.getInt("id");
			Long tokenl=this.getParaToLong("token");
			if(tokenl!=null){
				if(!TokenManager.validateToken(this, tokenName)){
					this.rendJson_(false, "会话令牌错误！",id,new Random().nextLong());
					return;
				}
			}
			otherSave(m);
			Date now=new Date();
			if (id != null && id != 0) {
				msg="修改成功！";
				m.set("update_time",now);//修改时间
				m.update();
			} else {
				msg="保存成功！";
				m.set("create_time",now);//创建时间
				m.save();
			}
			
			id = m.getInt("id");
			rendJson_(true,msg, id,new Random().nextLong());
		} catch (Exception e) {
			log.error("保存异常", e);
			rendJson_(false, "保存异常！");
			e.printStackTrace();
		}
	}
	/**
	 * 保存修改的其他操作
	 * @param m
	 */
	protected void otherSave(Model<M> m){
		
	}
	/**
	 * 其他查询操作
	 * @param seach
	 */
	protected void otherSeach(Seach seach) {
		
	}
	public void del() {
		try {
			Long id = this.getParaToLong(0);
			if (id == null||id==0L){
				String ids = this.getPara("ids");
				if (ids != null && !"".equals(ids)) {
					Db.update("delete from " + this.table.getName() + " where id in ("+ ids+ ")");
				} else {
					id = this.getParaToLong("ID");
				}
			}else{
				po = get(id);
				if(hashChild(id)==false){
					Db.deleteById(this.table.getName(), id);
				}else{
					rendJson_(false, "此数据有相关联的子集数据，请先删除子集数据项！");
					return;
				}
			}
			rendJson_(true, "删除成功！",id);
		} catch (Exception e) {
			log.error("删除异常", e);
			rendJson_(false, "删除异常！");
		}
	}
	
	/**是否有子集 针对树形数据*/
	private boolean hashChild(Long id){
		try{
		Table tableInfo = TableMapping.me().getTable(modelClass);
		if(tableInfo.hasColumnLabel("pid")){
			List<Record> list=Db.find("select * from "+tableInfo.getName()+" where pid=?", id);
			return list!=null&&list.isEmpty()==false;
		}
		}catch(Exception e){
			return false;
		}
		return false;
	}
	
	public void rendJson_(boolean success,String msg,Object... obj){
		Map<String,Object>json=new HashMap<String,Object>();
		json.put("success",success);
		json.put("msg",msg);
		if(obj!=null&&obj.length>0){
			json.put("obj",obj[0]);
			if(obj.length>1){
				json.put("tokenid",obj[1]);
			}
		}
		this.renderJson(json);
	}
	public void combotree() {
		List<Record> dataList =null;
		String sql="select id,name,pid from "+table.getName();
		int shopid=getParaToInt(0,0);
		
		if(shopid==0) dataList = Db.find(sql);
		else dataList = Db.find(sql+" where shop_id =?",shopid);
		
		List<TreeNode> list = new ArrayList<TreeNode>();
		TreeNode rootNode = new TreeNode();
		rootNode.setId(0);
		rootNode.setText("");
		rootNode.setIconCls("icon-home");
		rootNode.setCanChk(false);
		rootNode.setChecked(true);
		fillTree(dataList, rootNode,"name",true,null);
		list.add(rootNode);
		this.renderJson_(list);
	}
	public void combobox(){
		int shopid=getParaToInt(0,0);
		List<Record> list=null;
		String sql="select * from "+table.getName();
		if(shopid==0) 
			list = Db.find(sql);
		else 
			list = Db.find(sql+" where shop_id =?",shopid);
		
		this.renderJson(list);
	}
	
	/**
	 * 通过pid字段关联
	 * @param dataList 集合
	 * @param pnode 父节点
	 * @param cname 节点名称字段
	 */
	protected void fillTree(List<Record> dataList,TreeNode pnode,String cname,Boolean canChk,List<Long>ckidList) {
		List<TreeNode> childelist = new ArrayList<TreeNode>();
		for (Record m : dataList) {
			Integer pid_ = m.getInt("pid");
			if (pnode.getId() == pid_) {
				Integer id = m.getInt("id");
				TreeNode nodechild = new TreeNode();
				nodechild.setId(id);
				nodechild.setText(m.getStr(cname));
				nodechild.setCanChk(canChk);
				childelist.add(nodechild);
				if(ckidList!=null&&ArrayUtils.contains(ckidList.toArray(), id))
				nodechild.setChecked(true);
				fillTree(dataList, nodechild,cname,canChk,ckidList);
			}
		}
		if (childelist.isEmpty() == false && childelist.size() > 0) {
			pnode.setChildren(childelist);
		}
	}
	
	/**
	 * 返回easyui格式的列表数据
	 * @param page 分页数据
	 * @author 田俊
	 */
	public void rendDataGrid(Page<M> page){
		renderJson( new DataGrid<M>(page.getList(),page.getTotalRow()));
	}
	public void rendDataGrid(List<M> list){
		renderJson( new DataGrid<M>(list,list.size()));
	}
	
	/**通过Gson生成*/
	public void renderJson_(Object obj) {
		super.renderJson(new Gson().toJson(obj));
	}
	
	/**
	 * 打印工作情况
	 * @param status
	 * @param context
	 */
	public void createCommon(int status,String context,String name){
		new VestCommon()
		.set("context", context)
		.set("status", status)
		.set("name", name)
		.set("create_time", new Date())
		.save();
	}
}
